package com.ld.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

/**
 *  dubbo-admin 中dubbo服务中的方法显示不出来问题
 *     https://www.cnblogs.com/timfruit/p/12433931.html
 */
@EnableDubbo
@Configuration
public class DubboConfig {

    @Value("${dubbo.registry.address}")
    private String registry_address;
    @Value("${dubbo.metadata-report.address}")
    private String meta_report_address;

    // 2.7.0 版本以上
    // https://blog.csdn.net/wangxq0224/article/details/99304253
    //用于fix dubbo admin : "无元数据信息，请升级至Dubbo2.7及以上版本，或者查看application.properties中关于config center的配置，详见 这里"
    // https://github.com/apache/dubbo-admin/wiki/Dubbo-Admin%E9%85%8D%E7%BD%AE%E8%AF%B4%E6%98%8E
    @PostConstruct
    public void postInitAdminMeta() {
        final String REGISTRY_ADDRESS = "dubbo.registry.address";
        String registryAddress = registry_address;
        if (!StringUtils.hasText(registryAddress)) {
            return;
        }
        if (!registryAddress.startsWith("zookeeper")) {
            return;
        }

        //注册中心为zookeeper, 修复元数据问题

        String data = REGISTRY_ADDRESS + "=" + registryAddress;

        final String META_REPORT_ADDRESS = "dubbo.metadata-report.address";
        String reportAddress = meta_report_address;
        if (StringUtils.hasText(reportAddress)) {
            data = data + "\n" + META_REPORT_ADDRESS + "=" + reportAddress;
        }

//        log.info("\n== data: {}", data);


        //warn: 多个注册中心未测试
        String connectString = registryAddress.replace("zookeeper://", "");

        RetryPolicy retryPolicy = new RetryNTimes(2, 1000);
        CuratorFramework zkClient = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
        zkClient.start();
        try {
            String nodePath = "/dubbo/config/dubbo/dubbo.properties";
            if (zkClient.checkExists().forPath(nodePath) == null) {
                zkClient.create()
                        .creatingParentsIfNeeded()
                        .forPath(nodePath, data.getBytes());
            } else {
                zkClient.setData().forPath(nodePath, data.getBytes());
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            zkClient.close();
        }
    }
}